package com.smartplatform.security.service;

import com.smartplatform.mapper.SysUserMapper;
import com.smartplatform.pojo.MyBaseUser;
import com.smartplatform.pojo.SysUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * @Author 咕唧
 * @Date 2022/6/7 10:10
 * @Version 1.0
 * 当前类的作用是告诉spring security当前登录的用户的具体信息,然后spring security就可以进行判断了
 */
@Service
public class MyUserDetailService implements UserDetailsService {


    private SysUserMapper sysUserMapper;

    @Autowired
    public void setSysUserMapper(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }

    /**
     * 当我们登陆时会请求spring security提供的登陆接口，在接口里面 security能拿到我们传递的用户名
     * 然后用户名会被传递到这个方法
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询了用户信息
        SysUserInfo userInfo = sysUserMapper.findByName(username);

        //将数据保存到request,在失败的情况下可以知道登录的名字
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        request.setAttribute("username", username);
        //这里我们不查询权限,因为用户的信息可能是错误的,这样的情况下我们的查询是无效的
        Assert.notNull(userInfo, () -> {
            throw new UsernameNotFoundException("账号或者密码错误");
        });
        //将我们的信息保存到spring security给我们提供的对象中
        MyBaseUser user = new MyBaseUser(username, userInfo.getPassword(), new ArrayList<>());
        //设置角色id
        user.setUserId(userInfo.getUId());
        return user;
    }
}
